package com.zhuanzhuan.youpin.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhuanzhuan.youpin.dao.FailedMsgDao;
import com.zhuanzhuan.youpin.entity.EHandleStatus;
import com.zhuanzhuan.youpin.entity.FailedMsg;
import com.zhuanzhuan.youpin.service.IConsumerService;

@Service
public class ConsumerService implements IConsumerService {

    private static Logger logger = LoggerFactory.getLogger(ConsumerService.class);
    @Autowired
    private FailedMsgDao failedMsgDao;

    @Override
    public void test() {
        logger.info("---------------test test test-------------");
    }

    @Override
    public List<FailedMsg> getFailedMsgByTopicAndTags(String topic, String tags) {
        FailedMsg record = new FailedMsg();
        record.setTopicAndTags(topic+"|"+tags);
        record.setStatus(EHandleStatus.FAILED_STATUS.status());
        return failedMsgDao.selectByFailedMsgSize1000(record);
    }

    @Override
    public Integer addFailedMsg(FailedMsg failedMsg) {
        FailedMsg updateFailedMsg = new FailedMsg().setBodyHash(failedMsg.getBodyHash()).setTopicAndTags(failedMsg.getTopicAndTags())
                .setStatus(failedMsg.getStatus()).setUpdateTime(System.currentTimeMillis());
        int updateC = failedMsgDao.updateByTopicAndTagsAndBodyHash(updateFailedMsg);
        if (updateC == 1) {
            logger.info("addFailedMsg update FailedMsg success , topicAndTags={} body={} ", failedMsg.getTopicAndTags(), failedMsg.getBody());
            return updateC;
        }
        Integer c = failedMsgDao.insert(failedMsg);
        if (c == 1) {
            logger.info("Add new FailedMsg success , topicAndTags={} body={} ", failedMsg.getTopicAndTags(), failedMsg.getBody());
        }
        return c;
    }

    @Override
    public Integer onesEnd(Long failedMsgId, EHandleStatus status) {
        FailedMsg record = new FailedMsg();
        record.setId(failedMsgId);
        record.setStatus(status.status());
        record.setUpdateTime(System.currentTimeMillis());
        int c = failedMsgDao.updateByPrimaryKeySelectivePlus(record);
        logger.info("onesEnd success , failedMsgId={} status={} ", failedMsgId, status);
        return c;
    }

    @Override
    public Integer onecMqSuccess(String topicAndTags, String bodyHash) {
        FailedMsg record = new FailedMsg();
        record.setStatus(EHandleStatus.SUCCESS_STATUS.status());
        record.setBodyHash(bodyHash);
        record.setTopicAndTags(topicAndTags);
        record.setUpdateTime(System.currentTimeMillis());
        int c = failedMsgDao.updateBySelective(record);
        logger.info("OnecMqSuccess success , topicAndTags={} bodyHash={} ", topicAndTags, bodyHash);
        return c;
    }

}
